//
//  VRFirefightingRecordViewController.m
//  VRFirefighting
//
//  Created by Veer on 2018/8/18.
//  Copyright © 2018年 Veer. All rights reserved.
//

#import "VRFirefightingRecordViewController.h"

#import "VRFirefightingRecordFoldParentCell.h"
#import "VRFirefightingRecordFoldChildCell.h"
#import "VRFirefightingRecordModel.h"
#import "JKSelectorView.h"


@interface VRFirefightingRecordViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) JKSelectorView *selectorView;
@property (nonatomic, strong) UIButton *choseDateBtn;

@property (nonatomic, strong) NSArray<VRFirefightingRecordModel *> *recordModelArray;
@property (nonatomic, assign) NSInteger curSelectedIndex;

@end

@implementation VRFirefightingRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = ScrollViewBgColor;
    self.title = @"我的消防安全记录";
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self setupSubView];
    [self getRecord];
}

- (void)setupSubView
{
    [self.view addSubview:self.tableView];
    
    UIView *headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, NAVIGATION_BAR_HEIGHT, kScreenWidth, 70);
    [self.view addSubview:headerView];
    
    // 按钮
    UIButton *showAllBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    showAllBtn.backgroundColor = RGB(78, 173, 57);
    showAllBtn.layer.cornerRadius = 4;
    [showAllBtn setTitle:@"全部隐患" forState:UIControlStateNormal];
    showAllBtn.titleLabel.font = VRFont(16);
    [showAllBtn setTitleColor:RGB(255, 255, 255) forState:UIControlStateNormal];
    [showAllBtn setTitleColor:RGB(120, 120, 120) forState:UIControlStateHighlighted];
    [showAllBtn addTarget:self action:@selector(onShowAllBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:showAllBtn];
    [showAllBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.centerY.mas_equalTo(headerView);
        make.width.mas_equalTo(90);
        make.height.mas_equalTo(30);
    }];
    
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.backgroundColor = MAINColor;
    [searchBtn setTitle:@"隐患查询" forState:UIControlStateNormal];
    searchBtn.titleLabel.font = VRFont(16);
    [searchBtn setTitleColor:RGB(255, 255, 255) forState:UIControlStateNormal];
    [searchBtn setTitleColor:RGB(120, 120, 120) forState:UIControlStateHighlighted];
    [searchBtn addTarget:self action:@selector(onSearchBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:searchBtn];
    [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20);
        make.centerY.mas_equalTo(headerView);
        make.width.mas_equalTo(78);
        make.height.mas_equalTo(30);
    }];
    
    XButton *choseDateBtn = [XButton buttonWithType:UIButtonTypeCustom];
    //    goCardPackageBtn.layer.cornerRadius = 2;
    //    goCardPackageBtn.layer.borderColor = RGB(248, 177, 90).CGColor;
    choseDateBtn.layer.borderColor = MAINColor.CGColor;
    choseDateBtn.layer.borderWidth = 1.0;
    [choseDateBtn setTitle:@"选择时间" forState:UIControlStateNormal];
    choseDateBtn.titleLabel.font = VRFont(14);
    [choseDateBtn setTitleColor:RGB(120, 120, 120) forState:UIControlStateNormal];
    [choseDateBtn setTitleColor:RGB(211, 209, 209) forState:UIControlStateDisabled];
    choseDateBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
    [choseDateBtn setImage:[UIImage imageNamed:@"shearch"] forState:UIControlStateNormal];
    choseDateBtn.imageEdgeInsets = UIEdgeInsetsMake(8, 0, 8, 0);
    [choseDateBtn addTarget:self action:@selector(onChoseDateBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:choseDateBtn];
    self.choseDateBtn = choseDateBtn;
    [choseDateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(searchBtn.mas_left).offset(-2);
        make.centerY.mas_equalTo(headerView);
        if (kScreenWidth <= 375) {
            make.width.mas_equalTo(122 * ScreenScale);
        }else{
            make.width.mas_equalTo(122);
        }
        make.height.mas_equalTo(30);
    }];
    
    
}


#pragma mark - networking
- (void)getRecord
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"UserID"] = [VRUser shareUser].token;
//    param[@"fIsAreaManage"] = @([VRUser shareUser].fIsAreaManage);
    
    weakify(self)
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    [JKNetworking postWithSign:GetFirefightingRecord parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            self.recordModelArray = [VRFirefightingRecordModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.tableView reloadData];
                [hud hideAnimated:YES];
            });
        }else if(msg.length > 0){
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:msg];
                [hud hideAnimated:YES];
            });
        }
        [self.tableView.mj_header endRefreshing];
    } error:^(NSError * _Nonnull error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
            [hud hideAnimated:YES];
            [self.tableView.mj_header endRefreshing];
        });
    }];
}


- (void)searchRecordWith:(NSString *)year
{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"UserID"] = [VRUser shareUser].token;
    param[@"year"] = year;
    //    param[@"fIsAreaManage"] = @([VRUser shareUser].fIsAreaManage);
    
    weakify(self)
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    [JKNetworking postWithSign:SearchFirefightingRecord parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            self.recordModelArray = [VRFirefightingRecordModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.tableView reloadData];
                [hud hideAnimated:YES];
            });
        }else if(msg.length > 0){
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:msg];
                [hud hideAnimated:YES];
            });
        }
        [self.tableView.mj_header endRefreshing];
    } error:^(NSError * _Nonnull error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
            [hud hideAnimated:YES];
            [self.tableView.mj_header endRefreshing];
        });
    }];
}


#pragma mark - action
- (void)onShowAllBtnClick:(UIButton *)sender
{
    [self getRecord];
}

- (void)onSearchBtnClick:(UIButton *)sender
{
    [self searchRecordWith:[NSString stringWithFormat:@"%zd", (long)(1900 + self.curSelectedIndex)]];
}

- (void)onChoseDateBtnClick:(UIButton *)sender
{
    
    NSMutableArray *yearArray = [NSMutableArray array];
    for (int i = 1900; i < 2100; i++) {
        [yearArray addObject:[NSString stringWithFormat:@"%d年", i]];
    }
    self.selectorView.titleArray = [yearArray copy];
    
    [self.selectorView show];
    if (self.selectorView.curSelectedIndex == 0) {
        self.selectorView.curSelectedIndex = 2018 - 1900;
    }  
}


#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return self.recordModelArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 60;
}

-(CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    VRFirefightingRecordModel *pmodel = self.recordModelArray[section];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.tag = section + 1;
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonPress:) forControlEvents:UIControlEventTouchUpInside];
    button.frame = CGRectMake(0, 0, kScreenWidth, 60);
    
    UILabel *tlabel = [[UILabel alloc]initWithFrame:CGRectMake(120, (60-20)/2, 200, 20)];
    [tlabel setBackgroundColor:[UIColor clearColor]];
    [tlabel setFont:[UIFont systemFontOfSize:16]];
    tlabel.textColor = RGB(51, 51, 51);
    tlabel.text = pmodel.year;
    [button addSubview:tlabel];
    
    UIImageView *rightImageVIew = [[UIImageView alloc]initWithFrame:CGRectMake(kScreenWidth - 40, button.frame.size.height / 2 - 6 , 20, 12)];
    if (pmodel.unfold) {
        rightImageVIew.image = [UIImage imageNamed:@"fire_up"];
        
    } else {
        rightImageVIew.image = [UIImage imageNamed:@"fire_down"];
    }
    [button addSubview:rightImageVIew];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(button.frame) - 3, self.view.frame.size.width, 1)];
    lineView.frame = CGRectMake(0, CGRectGetHeight(button.frame) - 1, self.view.frame.size.width, 1);
    lineView.backgroundColor = RGB(220, 220, 220);
    
    [button addSubview:lineView];
    
    return  button;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    VRFirefightingRecordModel *model = self.recordModelArray[section];
    if (model.unfold) {
        return model.monthData.count;
    }
    return 0;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    VRFirefightingRecordModel *pmodel = self.recordModelArray[indexPath.section];
    VRFirefightingRecordMonthData *monthModel = pmodel.monthData[indexPath.row];
    if (monthModel.unfold) {
        return monthModel.dayData.count * 60 + 60;
    }else{
        
        return 60;
    }
    return 60;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    VRFirefightingRecordModel *pmodel = self.recordModelArray[indexPath.section];
    VRFirefightingRecordMonthData *monthModel = pmodel.monthData[indexPath.row];
    if (indexPath.row < pmodel.monthData.count) {
        
        VRFirefightingRecordFoldParentCell *cell = [VRFirefightingRecordFoldParentCell cellWith:tableView];
//        if (indexPath.row == 0 && cmodel.unfold) {
//            cell.lineView.backgroundColor = [UIColor colorFromHexRGB:@"0xdddddd"];
//        }
        cell.model = monthModel;
        return cell;
    }
    VRFirefightingRecordFoldChildCell *cell = [VRFirefightingRecordFoldChildCell cellWith:tableView];
    
    return cell;

}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    VRFirefightingRecordModel *pmodel = self.recordModelArray[indexPath.section];
    VRFirefightingRecordMonthData *monthModel = pmodel.monthData[indexPath.row];
    monthModel.unfold = !monthModel.unfold;

    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    //    [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:true];
}


#pragma mark-- headerButtonPress
- (void)buttonPress:(UIButton *)sender//headButton点击
{
    VRFirefightingRecordModel *pmodel = self.recordModelArray[sender.tag - 1];
    //判断状态值
    pmodel.unfold = !pmodel.unfold;
    
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:sender.tag-1] withRowAnimation:UITableViewRowAnimationAutomatic];

}


#pragma mark -- property
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT + 70, self.view.frame.size.width, self.view.frame.size.height - NAVIGATION_BAR_HEIGHT - 70) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.01)];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.sectionHeaderHeight = 0;
        _tableView.sectionFooterHeight = 0;
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
//        _tableView.backgroundColor = [UIColor whiteColor];
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return  _tableView;
}


- (JKSelectorView *)selectorView
{
    if (_selectorView == nil) {
        
        _selectorView = [[JKSelectorView alloc] init];
        _selectorView.title = nil;
        weakify(self)
        _selectorView.sureBlock = ^(NSString *value, NSInteger index) {
          
            strongify(self)
            self.curSelectedIndex = index;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.choseDateBtn setTitle:value forState:UIControlStateNormal];
            });
        };
    }
    return _selectorView;
}


@end
